import type { ModalFuncProps } from "antd/lib/modal/Modal";
import { message as Message, Modal, notification } from "antd";
import type { ConfigProps } from "antd/lib/notification";
import { isString } from "@/utils/is";
import Icon from "@/components/Icon";

export interface NotifyApi {
	info(config: Recordable): void;
	success(config: Recordable): void;
	error(config: Recordable): void;
	warn(config: Recordable): void;
	warning(config: Recordable): void;
	open(args: Recordable): void;
	close(key: string): void;
	config(options: ConfigProps): void;
	destroy(): void;
}

export declare type NotificationPlacement = "topLeft" | "topRight" | "bottomLeft" | "bottomRight";
export declare type IconType = "success" | "info" | "error" | "warning";
export interface ModalOptionsEx extends Omit<ModalFuncProps, "iconType"> {
	iconType: "warning" | "success" | "error" | "info";
}
export type ModalOptionsPartial = Partial<ModalOptionsEx> & Pick<ModalOptionsEx, "content">;

function getIcon(iconType: string) {
	if (iconType === "warning") return <Icon icon="ant-design:info-circle-filled" />;
	else if (iconType === "success") return <Icon icon="ant-design:check-circle-filled" />;
	else if (iconType === "info") return <Icon icon="ant-design:info-circle-filled" />;
	else return <Icon icon="ant-design:close-circle-filled" />;
}

function renderContent({ content }: Pick<ModalOptionsEx, "content">) {
	if (isString(content))
		return (
			<div>
				<div>{content}</div>
			</div>
		);
	else return content;
}

/**
 * @description: Create confirmation box
 */
function createConfirm(options: ModalOptionsEx) {
	const iconType = options.iconType || "warning";
	Reflect.deleteProperty(options, "iconType");
	const opt: ModalFuncProps = {
		centered: true,
		icon: getIcon(iconType),
		...options,
		content: renderContent(options)
	};
	return Modal.confirm(opt);
}

function getBaseOptions() {
	return {
		okText: "Ok",
		centered: true
	};
}

function createModalOptions(options: ModalOptionsPartial, icon: string): ModalOptionsPartial {
	return {
		...getBaseOptions(),
		...options,
		content: renderContent(options),
		icon: getIcon(icon)
	};
}

function createSuccessModal(options: ModalOptionsPartial) {
	return Modal.success(createModalOptions(options, "success"));
}

function createErrorModal(options: ModalOptionsPartial) {
	return Modal.error(createModalOptions(options, "close"));
}

function createInfoModal(options: ModalOptionsPartial) {
	return Modal.info(createModalOptions(options, "info"));
}

function createWarningModal(options: ModalOptionsPartial) {
	return Modal.warning(createModalOptions(options, "warning"));
}

notification.config({
	placement: "topRight",
	duration: 3
});

/**
 * @description: message
 */
export function useMessage() {
	return {
		createMessage: Message,
		notification: notification as NotifyApi,
		createConfirm,
		createSuccessModal,
		createErrorModal,
		createInfoModal,
		createWarningModal
	};
}
